<?php
namespace Admin\Controller;
class AccessController extends BaseController{

    //模型
    private $_mod;
    private $_nodeMod;
    private $_roleMod;

    //角色id
    private $rid;

    //构造函数
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('Access');
        $this->_nodeMod = D('Node');
        $this->_roleMod = D('Role');
        $this->rid = I('rid', 0, 'intval');
    }

    //设置权限
    public function edit()
    {
        $prefix = C('DB_PREFIX');
        if (IS_POST) {
            if ($this->_mod->editAccess()) {
                $this->success('操作成功', U('Role/index'));
            } else {
                $error = $this->_mod->getError();
                $this->error($error ? $error : "操作失败！");
            }
        } else {
            //角色ID
            $rid = I('get.rid', 0, 'intval');
            $sql = "SELECT n.nid,n.title,n.pid,n.type,a.rid as access_rid
                    FROM {$prefix}node AS n
                    LEFT JOIN (SELECT * FROM {$prefix}access WHERE rid={$rid}) AS a
                	ON n.nid = a.nid
                	ORDER BY list_order ASC, nid ASC";
            $result = $this->_mod->query($sql);
            $json = array();
            foreach ($result as $n => $rs) {
                //当前角色已经有权限或不需要验证的节点
                $checked = $rs['access_rid'] || $rs['type'] == 2 ? true : false;
                //不需要验证的节点，关闭选择（因为所有管理员都有权限）
                $disabled = $rs['type'] == 2 ? true : false;
                $data = array(
                    'nid' => $rs['nid'],
                    'pid' => $rs['pid'],
                    'name' => $rs['title'] . ($rs['type'] == 2 ? "(菜单项)" : ""),
                    'checked' => $checked,
                    'chkDisabled' => $disabled,
                );
                $json[] = $data;
            }
            $name = $this->_roleMod->where(array('rid'=>$rid))->getField('rname');
            $this->assign('rid', $rid);
            $this->assign('name', $name);
            $this->assign('json', $json);
            $this->display();
        }
    }
}